<template>
  <div class="agent-tree">
    <span class="del-arrow"></span>
    <el-popover ref="popover-tree" v-model.trim="popoverVisable" placement="bottom-start" visible-arrow="false" trigger="click" :disabled="disabled">
      <el-input
        size="mini"
        slot="reference"
        v-model="inputValue"
        :disabled="disabled"
        :placeholder="$t('public.pickAgentTip')">
        <i
          class="el-input__icon el-icon-close"
          slot="suffix"
          @click="handleInputIconClick">
        </i>
      </el-input>
      <el-tree-new
        :class="forChannelConfig?'forChannelConfig':'a-tree'"
        :height="forChannelConfig?200:300"
        ref="tree"
        node-key="_id"
        :data="optionData"
        show-checkbox
        accordion
        default-expand-all
        :filter-node-method="filterNode"
        @check="handleCheckChange">
      </el-tree-new>
    </el-popover>
  </div>
</template>
<script>
  import { scopeAgents } from '@/utils/m7Utils'
  import tree from '../../ui-modules/tree/src/tree.vue'
  import { deepClone } from '@/utils/m7Utils'
  export default {
    name: 'AgentTreeSelect',
    components: {
      'el-tree-new': tree
    },
    data () {
      return {
        popoverVisable: false,
        inputValue: '',
        optionData: [],
        checkedAgents: [],
        agentsList: []
      }
    },
    props: {
      disabled: {
        type: Boolean,
        default: false
      },
      moudule: String,
      forChannelConfig: {
        type: Boolean,
        default: false
      },
      agentCheckedIds: {
        type: Array,
        default: function () {
          return []
        }
      },
      checkedAgentsOfChannelConfigTree: {
        type: Array,
        default: function () {
          return []
        }
      },
      PBX: {
        type: String,
        default: ''
      }
    },
    watch: {
      inputValue (val) {
        this.$refs.tree.filter(val)
      },
      disabled (value) {
        if (value) {
          this.popoverVisable = false
        }
      },
      agentCheckedIds () {
//        this.setCheckedAgent(this.agentCheckedIds)
      },
      PBX () {
        if (this.forChannelConfig) {
          Promise.all([
            this.$store.dispatch('getCache', { type: 'depts' }),
            this.$store.dispatch('getCache', { type: 'agents' })
          ]).then(([depts, agents]) => {
            if (!this.PBX) {
              if (this.moudule) {
                agents = scopeAgents(this.moudule, agents)
              }
            } else {
              agents = this.$store.state.session.ivrMap[this.PBX].data.account_user
            }
            let optionData = []
            dealDept(depts, optionData, '')
            dealAgent(agents, optionData[0].children)
            this.agentsList = deepClone(agents).filter(agent => agent.status === 'enable')
            let noDeptAgents = agents.filter(agent => agent.status === 'enable' && !agent.deptId).map(agent => ({ _id: agent._id, type: 'agent', label: `${agent.displayName} ${agent.exten}`, pinyin: agent.pinyin }))
            optionData[0].children.push(...noDeptAgents)
            setDeptAgentCount(optionData[0])
            this.optionData = optionData
            this.$on('resetAgent', this.resetAgent1)
            this.$on('deleteAgent', this.deleteAgent1)
//            this.$on('resetAgent', () => {
//              this.resetAgent()
//            })
//            this.$on('deleteAgent', (_id) => {
//              this.deleteAgent(_id)
//            })
            if (this.agentCheckedIds.length > 0) {
//              this.setCheckedAgent(this.agentCheckedIds)
            }
          })
        }
      },
      checkedAgentsOfChannelConfigTree () {
        if (this.forChannelConfig) {
//          this.checkedAgents = this.checkedAgentsOfChannelConfigTree
        }
      },
      popoverVisable (val) {
        if (val) {
          this.$refs.tree.reset()
          if (this.forChannelConfig) {
            this.setCheckedAgent(this.agentCheckedIds)
          }
        }
      }
    },
    beforeDestroy: function () {
      this.$off('resetAgent', this.resetAgent1)
      this.$off('deleteAgent', this.deleteAgent1)
    },
    methods: {
      resetAgent1 () {
        this.resetAgent()
      },
      deleteAgent1: function (_id) {
        console.log(_id)
        this.deleteAgent(_id)
      },
      resetAgent () {
        this.$refs.tree.setCheckedKeys([])
      },
      deleteAgent (key) {
        this.$refs.tree.setChecked(key, false)
      },
      setCheckedAgent (ids) {     //  回显时触发
        this.$refs.tree.setCheckedKeys(ids)
      },
      handleInputIconClick () {
        this.inputValue = ''
      },
      filterNode (value, data) {
        if (!value) return true
        return data.type === 'agent' && (data.label.indexOf(value) !== -1 || data.pinyin.indexOf(value) !== -1)
      },
      handleCheckChange () {
        // 判断是否添加删除坐席
        let checkNode = this.$refs.tree.getCheckedNodes()
        let checkedAgents = checkNode.filter(node => node.type === 'agent').map(node => {
          return {_id: node._id, displayName: node.label.split(' ')[0], exten: node.label.split(' ')[1]}
        })
        this.checkedAgents = checkedAgents
        let hash = {}
        this.checkedAgents = this.checkedAgents.reduce(function (item, next) {
          hash[next._id] ? '' : hash[next._id] = true && item.push(next)
          return item
        }, [])
        this.$emit('agent-change', this.checkedAgents)
      }
    },
    beforeMount () {
      Promise.all([
        this.$store.dispatch('getCache', { type: 'depts' }),
        this.$store.dispatch('getCache', { type: 'agents' })
      ]).then(([depts, agents]) => {
        if (!this.PBX) {
          if (this.moudule) {
            agents = scopeAgents(this.moudule, agents)
          }
        } else {
          agents = this.$store.state.session.ivrMap[this.PBX].data.account_user
        }
        console.log(agents)
        let optionData = []
        dealDept(depts, optionData, '')
        dealAgent(agents, optionData[0].children)
        this.agentsList = deepClone(agents).filter(agent => agent.status === 'enable')
        let noDeptAgents = agents.filter(agent => agent.status === 'enable' && !agent.deptId).map(agent => ({ _id: agent._id, type: 'agent', label: `${agent.displayName} ${agent.exten}`, pinyin: agent.pinyin }))
        optionData[0].children.push(...noDeptAgents)
        setDeptAgentCount(optionData[0])
        this.optionData = optionData
        this.$on('resetAgent', this.resetAgent1)
        this.$on('deleteAgent', this.deleteAgent1)
//        this.$on('resetAgent', () => {
//          this.resetAgent()
//        })
//        this.$on('deleteAgent', (_id) => {
//          this.deleteAgent(_id)
//        })
        if (this.agentCheckedIds.length > 0) {
//          this.setCheckedAgent(this.agentCheckedIds)
        }
        if (this.forChannelConfig) {
          this.checkedAgents = this.checkedAgentsOfChannelConfigTree
        }
      })
    }
  }
  function dealDept (depts, arr, key) {
    for (let i = 0; i < depts.length; i++) {
      let dept = depts[i]
      if (dept.pId === key) {
        let obj = {
          _id: dept._id,
          type: 'dept',
          label: dept.name,
          order: dept.order,
          children: []
        }
        arr.push(obj)
        dealDept(depts, obj.children, dept._id)
      }
    }
  }
  function dealAgent (agents, arr) {
    if (!arr) {
      return
    }
    for (let i = 0; i < arr.length; i++) {
      dealAgent(agents, arr[i].children)
      let deptAgents = agents.filter(agent => agent.status === 'enable' && agent.deptId === arr[i]._id)
      deptAgents = deptAgents.map(agent => ({ _id: agent._id, type: 'agent', label: `${agent.displayName} ${agent.exten}`, pinyin: agent.pinyin }))
      arr[i].children.push(...deptAgents)
    }
  }

  function setDeptAgentCount (obj) {
    if (!obj.children && obj.type === 'agent') {
      return 1
    }

    let count = 0
    for (let i = 0; i < obj.children.length; i++) {
      count += setDeptAgentCount(obj.children[i])
    }

    obj.label = `${obj.label} (${count})`
    return count
  }
</script>
<style lang="stylus" scoped>
.el-checkbox
  padding-right 0
.a-tree
  max-height 300px
  min-width 190px
  overflow-y auto
.forChannelConfig
  max-height 200px
  min-width 250px
  max-width 450px
  overflow scroll
</style>
